const Mysql = require('node-mysql-promise')

let mysqlConnPool;
function start() {
    mysqlConnPool = Mysql.createConnection({
        host: '172.17.70.41',
        user: 'remote',
        password: 'NBqKfEFr',
        database: 'sms',
        trace : false
    });
}

//模块加载直接初始化mysql
start();

module.exports = {
    start,
    end: function () {
        mysqlConnPool.close()
    },
    getMobileInfo: async function (mobile) {
        try {
            // 强制转换为字符串
            mobile = String(mobile).trim();
            if (!mobile || mobile.length < 11) {
                return null;
            }
            let province_mobile_seg = mobile.substr(0, 7)
            
            let result = await mysqlConnPool.table('operator_province_mobile_segment').alias('a').field('a.remark, province_name,area_name').join({
                table: 'province_area_info',
                join: 'left',//left, right, inner三种方式
                as: 'b', //表别名
                on: ['province_id', 'province_id'] //ON 条件
            }).where({ province_mobile_seg }).find()
            console.log(result)
            // 处理查询结果为空的情况
            if (!result || Object.keys(result).length === 0) {
                console.info(`No record found for mobile segment: ${province_mobile_seg}`);
                return null;
            }
            
            return {
                isp: result.remark,
                area_p: result.province_name,
                area_c: result.area_name
            }
        } catch (err) {
            console.error(`Database query error for mobile: ${mobile}`, err);
            return null;
        }
    }
}
